package com.jianyun.jyzs.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.jianyun.jyzs.R;
import com.jianyun.jyzs.base.MVPBaseActivity;
import com.jianyun.jyzs.bean.EnterInfo;
import com.jianyun.jyzs.bean.UserInfo;
import com.jianyun.jyzs.dao.LoginDao;
import com.jianyun.jyzs.presenter.UpdataPwdPresenter;
import com.jianyun.jyzs.utils.LoginCache;
import com.jianyun.jyzs.utils.UtilsStyle;
import com.jianyun.jyzs.view.iview.IUpdataPwdView;
import com.jianyun.jyzs.widget.ClearWriteEditText;
import com.jrmf360.rylib.common.util.KeyboardUtil;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;


/**
 * 修改密码
 * Created by yangshijun on 2018/5/28.
 */

public class SetPasswordActivity extends MVPBaseActivity<IUpdataPwdView, UpdataPwdPresenter> implements IUpdataPwdView {


    @BindView(R.id.originPassword)
    ClearWriteEditText originPassword;
    @BindView(R.id.newPassword)
    ClearWriteEditText newPasswords;
    @BindView(R.id.confirmPassword)
    ClearWriteEditText confirmPassword;
    @BindView(R.id.changePasswordToast)
    TextView infoPromptToast;

    private TextView optionsTextView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        UtilsStyle.setStatusBarMode(this,true);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.rce_activity_set_password);
        ButterKnife.bind(this);
        initEditTextListener();
    }

    @NonNull
    @Override
    public UpdataPwdPresenter createPresenter() {
        return new UpdataPwdPresenter();
    }

    private boolean isPasswordLengthValid(String password) {
        if (TextUtils.isEmpty(password)) {
            return false;
        }
        if (password.length() >= 6 && password.length() <= 16) {
            return true;
        }
        return false;
    }

    @Override
    public void onCreateActionBar(ActionBar actionBar) {
        final View actionBarView = actionBar.setActionBar(R.layout.rce_actionbar_option_text);
        ImageButton backImgBtn = (ImageButton) actionBarView.findViewById(R.id.imgbtn_custom_nav_back);
        backImgBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        TextView titleTextView = (TextView) actionBarView.findViewById(R.id.tv_custom_nav_title);
        titleTextView.setText(R.string.rce_change_password_title);
        optionsTextView = (TextView) actionBarView.findViewById(R.id.tv_custom_nav_option);
        optionsTextView.setText(R.string.rce_OK);
        setOptionsTextEnable(false);
        optionsTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String originalPassword = originPassword.getText();
                String newPassword = newPasswords.getText().toString();
                String confirmNewPassword = confirmPassword.getText().toString();
                if (TextUtils.isEmpty(originalPassword) ||
                        TextUtils.isEmpty(newPassword) ||
                        TextUtils.isEmpty(confirmNewPassword)) {
                    infoPromptToast.setVisibility(View.VISIBLE);
                    infoPromptToast.setText(R.string.rce_change_password_empty);
                    return;
                }
                if (!isPasswordLengthValid(newPassword) ||
                        !isPasswordLengthValid(confirmNewPassword)) {
                    infoPromptToast.setVisibility(View.VISIBLE);
                    infoPromptToast.setText(R.string.rce_password_format_error);
                    return;
                }
                if (!newPassword.equals(confirmNewPassword)) {
                    infoPromptToast.setVisibility(View.VISIBLE);
                    infoPromptToast.setText(R.string.rce_change_password_not_equal);
                    return;
                }
                if (originalPassword.equals(newPassword)) {
                    infoPromptToast.setVisibility(View.VISIBLE);
                    infoPromptToast.setText(R.string.rce_change_password_equal);
                    return;
                }
                KeyboardUtil.hideKeyboard(SetPasswordActivity.this);
                //修改密码
                updataPwd(originalPassword,newPassword);

            }
        });
    }

    /**
     * 修改密码
     * @param oldPwd
     * @param newPwd
     */
    private void updataPwd(String oldPwd,String newPwd){
        String userId = LoginCache.getInstance().getUserInfo().getUserId();
        String enterpriseCode = LoginCache.getInstance().getLoginCache().getEnterpriseCode();
        getPresenter().updataPwd(enterpriseCode,userId,oldPwd,newPwd);
    }

    private void initEditTextListener() {
        originPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                hidePromptToast();
                handleTextChanged();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        newPasswords.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                hidePromptToast();
                handleTextChanged();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        confirmPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                hidePromptToast();
                handleTextChanged();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }
    private void hidePromptToast() {
        if (infoPromptToast.getVisibility() == View.VISIBLE) {
            infoPromptToast.setText(null);
        }
    }

    private void handleTextChanged() {
        String originalPassword = originPassword.getText();
        String newPassword = newPasswords.getText().toString();
        String confirmNewPassword = confirmPassword.getText().toString();
        if (newPassword.length() >= 6 && confirmNewPassword.length() >= 6) {
            setOptionsTextEnable(true);
        } else {
            setOptionsTextEnable(false);
        }
    }

    private void setOptionsTextEnable(boolean enable) {
        optionsTextView.setClickable(enable);
        optionsTextView.setTextColor(enable ? getResources().getColor(R.color.color_primary) :
                getResources().getColor(R.color.color_button_blue_disabled));
    }


    @Override
    public void onSuccess() {
        Toast.makeText(SetPasswordActivity.this, R.string.rce_update_success, Toast.LENGTH_SHORT).show();
        UserInfo userInfo = LoginCache.getInstance().getUserInfo();
        LoginCache.getInstance().setUserInfo(userInfo.getAccount(),"",userInfo.getUserId());
        String enterpriseCode = LoginCache.getInstance().getLoginCache().getEnterpriseCode();
        //数据库中插入
        EnterInfo enterInfo = new EnterInfo();
        enterInfo.setAccount(userInfo.getAccount());
        enterInfo.setPassword("");
        enterInfo.setEnterinfo(enterpriseCode);
        LoginCache.getInstance().setLoginTure(false);
        LoginDao loginDao = new LoginDao(SetPasswordActivity.this);
        int enterInfoID = loginDao.getEnterInfoID(enterInfo);
        enterInfo.setAutoId(enterInfoID);
        loginDao.update(enterInfo);
        startActivity(new Intent(this,LoginActivity.class));
        finish();
    }

    @Override
    public void onFailed() {
        infoPromptToast.setVisibility(View.VISIBLE);
        infoPromptToast.setText(R.string.rce_change_password_error_prompt);
    }

    @Override
    public void onException(String msg) {
        infoPromptToast.setVisibility(View.VISIBLE);
        infoPromptToast.setText(msg);
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hintLoading() {

    }
}
